package jaux.tank.api.controller.system;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import jaux.tank.api.controller.BaseController;
import jaux.tank.bean.annotion.core.BussinessLog;
import jaux.tank.bean.constant.factory.PageFactory;
import jaux.tank.bean.constant.state.ManagerStatus;
import jaux.tank.bean.dictmap.UserDict;
import jaux.tank.bean.dto.UserDto;
import jaux.tank.bean.entity.system.User;
import jaux.tank.bean.enumeration.BizExceptionEnum;
import jaux.tank.bean.exception.TankException;
import jaux.tank.bean.vo.front.Ret;
import jaux.tank.bean.vo.front.Rets;
import jaux.tank.dao.system.UserRepository;
import jaux.tank.factory.UserFactory;
import jaux.tank.service.system.UserService;
import jaux.tank.utils.BeanUtil;
import jaux.tank.utils.MD5;
import jaux.tank.utils.StringUtils;
import jaux.tank.utils.ToolUtil;
import jaux.tank.utils.factory.Page;
import jaux.tank.warpper.UserWarpper;

/**
 * UserController
 *
 * @author zt
 * @version 2018/9/15 0015
 */
@RestController("userApiController")
@RequestMapping("/api/user")
public class UserController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserService userService;
    
    @ApiOperation(value = "查询用户列表")
    @GetMapping("/list")
    public Ret<Page<User>> list(@RequestParam(required = false) String account,
                       @RequestParam(required = false) String name,
                       @RequestParam(required = false) String beginTime,
                       @RequestParam(required = false) String endTime,
                       @RequestParam(required = false) String roleId,
                       @RequestParam(required = false) Integer deptid){
        Map<String,Object> params = new HashMap<>();
        params.put("nameLike",name);
        params.put("beginTime",beginTime);
        params.put("endTime",endTime);
        params.put("roleId",roleId);
        if(deptid!=null&&deptid!=0){
            params.put("deptid",deptid);
        }

        Page<User> page =  userService.findPage(new PageFactory<User>().defaultPage(), params);
        List list = (List) new UserWarpper(BeanUtil.objectsToMaps(page.getRecords())).warp();
        page.setRecords(list);
        return Rets.success(page);
    }
    @ApiOperation("查询用户信息")
    @GetMapping("/info")
    public Ret<User> info(@RequestParam String userId){
    	User user = userRepository.findById(userId).orElse(null);
    	return Rets.success(user);
    }
    
    @ApiOperation(value = "编辑用户")
    @PostMapping
//    @BussinessLog(value = "编辑管理员", key = "name", dict = UserDict.class)
    public Ret<Object> save(@RequestBody UserDto user,BindingResult result){

        if(user.getId()==null) {
            // 判断账号是否重复
            User theUser = userRepository.findByAccount(user.getAccount());
            if (theUser != null) {
                throw new TankException(BizExceptionEnum.USER_ALREADY_REG);
            }
            // 完善账号信息
            user.setSalt(ToolUtil.getRandomString(5));
            user.setPassword(MD5.md5(user.getPassword(), user.getSalt()));
            user.setStatus(ManagerStatus.OK.getCode());
            user.setCreatetime(new Date());
            userRepository.save(UserFactory.createUser(user, new User()));
        }else{
            userRepository.findById(user.getId()).ifPresent(oldUser->{
            	userRepository.save(UserFactory.updateUser(user,oldUser));
            });
        }
        return Rets.success();
    }

    @ApiOperation(value = "删除用户")
    @BussinessLog(value = "删除管理员", key = "userId", dict = UserDict.class)
    @DeleteMapping
    public Ret<Object> remove(String userId){
        logger.info("id:{}",userId);
        if (ToolUtil.isEmpty(userId)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        userRepository.findById(userId).ifPresent(user->{
        	user.setStatus(ManagerStatus.DELETED.getCode());
        	userRepository.save(user);
        	
        });
        return Rets.success();
    }
}
